import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, ScrollView, Dimensions, Platform, Linking, Alert, Image } from 'react-native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import Ionicons from 'react-native-vector-icons/Ionicons';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { RechargeApi } from '../../instance/api';
import { WebView } from 'react-native-webview';
import AsyncStorage from '@react-native-async-storage/async-storage';

const MAX_WIDTH = 480;
const screenWidth = Dimensions.get('window').width;
const contentWidth = screenWidth > MAX_WIDTH ? MAX_WIDTH : screenWidth;

const banks = [
  { name: '工商银行储蓄卡', tail: '5632' },
  { name: '建设银行储蓄卡', tail: '4641' },
  { name: '农业银行储蓄卡', tail: '3519' },
];

export default function Recharge({ navigation }) {
  const [amount, setAmount] = useState('0');
  const [payType, setPayType] = useState('wechat');
  const [showBankList, setShowBankList] = useState(false);
  const [selectedBank, setSelectedBank] = useState(1);
  const [isFocused, setIsFocused] = useState(false);

  const handleRecharge = async () => {
    if (!amount || parseFloat(amount) <= 0) {
      Alert.alert('错误', '请输入有效金额');
      return;
    }

    try {
      const response = await fetch('http://192.168.78.1:3000/pay/alipay', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ amount: parseFloat(amount) }),
      });
      const result = await response.json();

      if (result.code === 200) {
        // 充值成功后，累加金额
        const currentMoney = await AsyncStorage.getItem('money');
        const newMoney = (parseFloat(currentMoney) + parseFloat(amount)).toString();
        await AsyncStorage.setItem('money', newMoney);
        // Alert.alert('成功', '充值成功');
        navigation.navigate('AlipayWebView', { html: result.data });
      } else {
        Alert.alert('错误', '创建支付订单失败');
      }
    } catch (error) {
      console.error('支付请求失败:', error);
      Alert.alert('错误', '支付请求失败');
    }
  };

  // 添加支付结果处理
  useEffect(() => {
    const handleDeepLink = (event) => {
      if (event.url.startsWith('echioh://pay/result')) {
        // 处理支付结果
        const params = new URLSearchParams(event.url.split('?')[1]);
        const tradeStatus = params.get('trade_status');

        if (tradeStatus === 'TRADE_SUCCESS') {
          Alert.alert('成功', '充值成功！');
          // 这里可以添加刷新用户余额等操作
        } else {
          Alert.alert('提示', '支付未完成');
        }
      }
    };

    // 监听深度链接
    Linking.addEventListener('url', handleDeepLink);

    // 检查是否是通过深度链接打开的
    Linking.getInitialURL().then(url => {
      if (url) {
        handleDeepLink({ url });
      }
    });

    return () => {
      // 清理监听器
      Linking.removeAllListeners('url');
    };
  }, [navigation]);

  return (
    <ScrollView style={{ backgroundColor: '#f7f7f7' }} contentContainerStyle={{ alignItems: 'center', minHeight: hp('100%') }}>
      <View style={[styles.content, { width: contentWidth }]}>
        {/* 顶部标题 */}
        <View style={styles.headerWrap}>
          <TouchableOpacity onPress={() => navigation && navigation.goBack()} style={styles.headerBack}>
            <Ionicons name="chevron-back" size={wp('7%')} color="#222" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>余额充值</Text>
        </View>
        {/* 金额输入框 */}
        <View style={[styles.sectionBox, isFocused ? styles.sectionBoxFocused : null]}>
          <Text style={styles.sectionLabel}>充值金额</Text>
          <View style={styles.inputBox}>
            <Text style={styles.inputPrefix}>￥</Text>
            <TextInput
              style={styles.input}
              value={amount}
              onChangeText={setAmount}
              keyboardType="numeric"
              placeholder="请输入金额"
              placeholderTextColor="#bbb"
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(false)}
            />
          </View>
        </View>
        {/* 支付方式 */}
        <View style={styles.sectionBox2}>
          <Text style={styles.sectionLabel2}>充值方式</Text>
          <TouchableOpacity style={styles.payItem} onPress={() => setPayType('wechat')}>
            <MaterialCommunityIcons name="wechat" size={wp('7%')} color="#4ACF50" style={styles.payIcon} />
            <Text style={styles.payText}>微信支付</Text>
            {payType === 'wechat' && <Ionicons name="checkmark-circle" size={wp('5%')} color="#d0021b" style={styles.payCheck} />}
          </TouchableOpacity>
          <TouchableOpacity style={styles.payItem} onPress={() => setPayType('alipay')}>
            <Image source={require('../../game/17.png')} style={{ width: 20, height: 20, marginRight: 10, }} />
            <Text style={styles.payText}>支付宝</Text>
            {payType === 'alipay' && <Ionicons name="checkmark-circle" size={wp('5%')} color="#d0021b" style={styles.payCheck} />}
          </TouchableOpacity>
          <TouchableOpacity style={styles.payItem} onPress={() => setPayType('bank')}>
            <Ionicons name="card" size={wp('7%')} color="#2196F3" style={styles.payIcon} />
            <Text style={styles.payText}>银行卡</Text>
            <Ionicons name={showBankList ? 'chevron-up' : 'chevron-down'} size={wp('5%')} color="#bbb" style={styles.payArrow} onPress={() => setShowBankList(!showBankList)} />
            {payType === 'bank' && <Ionicons name="checkmark-circle" size={wp('5%')} color="#d0021b" style={styles.payCheck} />}
          </TouchableOpacity>
          {/* 银行卡下拉列表 */}
          {payType === 'bank' && showBankList && (
            <View style={styles.bankList}>
              {banks.map((bank, idx) => (
                <TouchableOpacity key={bank.tail} style={styles.bankItem} onPress={() => setSelectedBank(idx)}>
                  <Text style={styles.bankText}>{bank.name} ({bank.tail})</Text>
                  {selectedBank === idx && <Ionicons name="checkmark-circle" size={wp('4.5%')} color="#d0021b" style={styles.payCheck} />}
                </TouchableOpacity>
              ))}
              <TouchableOpacity style={styles.addBank}>
                <Ionicons name="add-circle-outline" size={wp('5%')} color="#bbb" style={{ marginRight: 6 }} />
                <Text style={styles.addBankText}>添加银行卡</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
        {/* 充值按钮 */}
        <TouchableOpacity style={styles.chargeBtn} onPress={() => handleRecharge()}>
          <Text style={styles.chargeBtnText}>充值</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  content: {
    backgroundColor: '#fff',
    marginTop: hp('2%'),
    borderRadius: 10,
    paddingBottom: 20,
    alignSelf: 'center',
    width: '100%',
    maxWidth: MAX_WIDTH,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
  },
  headerWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 50,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    marginBottom: 10,
    backgroundColor: '#fff',
    position: 'relative',
  },
  headerBack: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 50,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 2,
  },
  headerTitle: {
    fontSize: wp('4.5%') > 20 ? 20 : wp('4.5%'),
    color: '#222',
    fontWeight: 'bold',
    textAlign: 'center',
  },
  sectionBox: {
    backgroundColor: '#f7f7f7',
    borderRadius: 6,
    borderWidth: 0,
    borderColor: 'transparent',
    marginHorizontal: 12,
    marginBottom: 16,
    padding: 0,
    paddingTop: 8,
    paddingBottom: 8,
    marginTop: 0,
  },
  sectionBoxFocused: {
    borderWidth: 2,
    borderColor: '#3b7cff',
  },
  sectionLabel: {
    fontSize: wp('3.5%') > 15 ? 15 : wp('3.5%'),
    color: '#222',
    fontWeight: 'bold',
    marginLeft: 12,
    marginBottom: 6,
  },
  inputBox: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderRadius: 6,
    paddingHorizontal: 12,
    paddingVertical: 10,
    marginHorizontal: 8,
    borderWidth: 0,
  },
  inputPrefix: {
    fontSize: wp('5%') > 22 ? 22 : wp('5%'),
    color: '#888',
    marginRight: 6,
  },
  input: {
    flex: 1,
    fontSize: wp('5%') > 22 ? 22 : wp('5%'),
    color: '#222',
    padding: 0,
  },
  sectionBox2: {
    backgroundColor: '#f7f7f7',
    borderRadius: 6,
    marginHorizontal: 12,
    marginBottom: 16,
    paddingTop: 8,
    paddingBottom: 8,
    marginTop: 0,
  },
  sectionLabel2: {
    fontSize: wp('3.5%') > 15 ? 15 : wp('3.5%'),
    color: '#222',
    fontWeight: 'bold',
    marginLeft: 12,
    marginBottom: 6,
  },
  payItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderRadius: 6,
    marginHorizontal: 8,
    marginBottom: 8,
    paddingVertical: 10,
    paddingHorizontal: 10,
    position: 'relative',
  },
  payIcon: {
    marginRight: 10,
  },
  payText: {
    fontSize: wp('3.8%') > 16 ? 16 : wp('3.8%'),
    color: '#222',
    flex: 1,
  },
  payArrow: {
    marginLeft: 6,
  },
  payCheck: {
    marginLeft: 6,
  },
  bankList: {
    backgroundColor: '#fff',
    borderRadius: 6,
    marginHorizontal: 8,
    marginTop: 2,
    paddingVertical: 4,
    paddingHorizontal: 0,
    borderWidth: 0,
  },
  bankItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
  },
  bankText: {
    fontSize: wp('3.5%') > 15 ? 15 : wp('3.5%'),
    color: '#222',
    flex: 1,
  },
  addBank: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 10,
    paddingHorizontal: 12,
  },
  addBankText: {
    fontSize: wp('3.5%') > 15 ? 15 : wp('3.5%'),
    color: '#888',
  },
  chargeBtn: {
    backgroundColor: '#d0021b',
    borderRadius: 6,
    marginHorizontal: 12,
    marginTop: 20,
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
  },
  chargeBtnText: {
    color: '#fff',
    fontSize: wp('4.5%') > 20 ? 20 : wp('4.5%'),
    fontWeight: 'bold',
  },
});
